import Input from "@/components/Input";
import NavBar from "@/components/NavBar";
import { useFormik } from "formik";
import styles from "./index.module.scss";

import * as Yup from "yup";
import { useEffect, useRef, useState } from "react";
import { loginAction, sendCodeAction } from "@/store/action/user";
import { useAppDispatch } from "@/store";
import { Toast } from "antd-mobile";

export default function Login() {
  const dispatch = useAppDispatch();
  const formik = useFormik({
    initialValues: {
      mobile: "13566661111",
      code: "",
    },
    onSubmit: async (values) => {
      await dispatch(loginAction(values.mobile, values.code));
    },

    validationSchema: Yup.object().shape({
      mobile: Yup.string()
        .required("不能为空")
        .matches(/^1[3-9]\d{9}$/, "请输入11位的手机号码"),
      code: Yup.string()
        .required("不能为空")
        .matches(/^\d{6}$/, "请输入6位验证码"),
    }),
  });
  const [second, setSecond] = useState(0);
  const timerIdRef = useRef(0);

  const handleSendCode = () => {
    if (!formik.values.mobile) {
      Toast.show({ content: "手机号码不能为空", icon: "fail" });
      return;
    }
    Toast.show({ content: "发送成功", icon: "success" });

    setSecond(60);
    dispatch(sendCodeAction(formik.values.mobile));

    timerIdRef.current = window.setInterval(() => {
      setSecond((preSecond) => {
        if (preSecond === 1) {
          clearInterval(timerIdRef.current);
        }
        return preSecond - 1;
      });
    }, 1000);
  };

  useEffect(() => {
    return () => {
      clearInterval(timerIdRef.current);
    };
  }, []);

  return (
    <div className={styles.root}>
      <NavBar />

      <div className="content">
        <h3>短信登录</h3>
        <form onSubmit={formik.handleSubmit}>
          <Input
            autoFocus
            className="input"
            placeholder="请输入手机号"
            autoComplete="off"
            type="text"
            name="mobile"
            maxLength={11}
            errorMsg={formik.touched.mobile ? formik.errors.mobile : ""}
            value={formik.values.mobile}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
          />

          <Input
            placeholder="请输入验证码"
            autoComplete="off"
            type="text"
            name="code"
            maxLength={6}
            errorMsg={formik.touched.code ? formik.errors.code : ""}
            extra={
              second === 0 ? (
                <span onClick={handleSendCode}>获取验证码</span>
              ) : (
                `${second}后获取数据`
              )
            }
            value={formik.values.code}
            onChange={formik.handleChange}
            onBlur={formik.handleBlur}
          />

          <button
            type="submit"
            className="login-btn"
            disabled={!formik.isValid}
          >
            登录
          </button>
        </form>
      </div>
    </div>
  );
}
